package com.lh.controller;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.PrivateKey;

/**
 * @author: linghao
 * @since: 2022/5/14
 */
@RequestMapping("nacosConfig")
@RestController
//@RefreshScope
public class NacosConfigDemoController {

    @NacosValue(value = "${name:zhangsan}",autoRefreshed = true)
    private String testStr;

    /*
        问题：1、nacos配置必须在bootsrap.yaml中才起作用
             2、通过@Value不能实时动态的获取配置，因为value注解不支持
                实时获取方式：
                    1）：@RefreshScope可以实时刷新@Value
                    2）：实现监听器
                    3）：从ConfigurableApplicationContext环境上下文获取
     */
    @Value("${server1.port:8081}")
    private String nacosServer1Config;

    @Autowired
    private ConfigurableApplicationContext configurableApplicationContext;

    @GetMapping("/get")
    public String getTestStr(){
        return testStr;
    }

    @GetMapping("/getservice1")
    public String getservice1(){
        return nacosServer1Config;
    }
    @GetMapping("/getservice2")
    public String getservice2(){
        return configurableApplicationContext.getEnvironment().getProperty("server1.port");
    }

    @GetMapping("/testConfigService")
    public String testConfigService(){
        try {
            ConfigService configService = NacosFactory.createConfigService("127.0.0.1:8848");
            boolean b = configService.publishConfig("service4.yaml", "TEST_GROUP", "publicTest=3", ConfigType.YAML.getType());
            boolean b2 = configService.publishConfig("service5.yaml", "TEST_GROUP", "publicTest=3");
            System.out.println("xxxxx "+b);
            System.out.println("xxxxx "+b2);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return testStr;
    }

}
